class Prop {
  static mapping = {
    table 'yuying_prop'
    key column:'prop_key'
    value column:'prop_value'
  }
  String key
  String value
  Long  objRefId
  String objRefClass
  Date dateCreated
  Date lastUpdated
  static constraints = {
  }

  def getObj() {
    getClass().classLoader.loadClass(objRefClass).get(objRefId)
  }

  def findAllByObj(obj) {
    if(obj.id){
       Prop.findAllByObjRefIdAndObjRefClass(obj.id, obj.class.name)
    }
  }

  def countByObj(obj) {
    if(obj.id){
      Prop.countByObjRefIdAndObjRefClass(obj.id, obj.class.name)
    }
  }

  static getPropValue(obj, key, String defaultValue = null){
    if(obj.id){
      def props = Prop.findAllByObjRefIdAndObjRefClassAndKey(obj.id, obj.class.name, key)
      if(props){
        return props[0].value
      }
    }
    return defaultValue
  }

  static setPropValue(obj, key, value){
    if(obj.id){
      def props = Prop.findAllByObjRefIdAndObjRefClassAndKey(obj.id, obj.class.name, key)
      if(props){
        def oldProp =  props[0]
        oldProp.value = value
        oldProp.save()
      } else {
        def prop = new Prop(
                key:key,
                value:value,
                objRefId:obj.id,
                objRefClass:obj.class.name,
        )
        prop.save()
      }
    }
    
  }
}
